package de.carcophan.archiver;

import com.google.inject.Guice;
import com.google.inject.Injector;
import de.carcophan.archiver.gui.ArchiveWindow;
import de.carcophan.archiver.guice.ArchiverModule;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Created by  on 15.04.2014.
 */
public class AppController extends Application {

  private static final Logger logger = LogManager.getLogger(AppController.class);

  private Injector injector;

  private ArchiveWorker worker;

  public AppController() {
  }

  @Override
  public void init() {
    logger.debug("AppController.init(),  ", new Object[]{});
    injector = Guice.createInjector(new ArchiverModule());
    worker = injector.getInstance(ArchiveWorker.class);
  }

  @Override
  public void start(Stage stage) throws Exception {

    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
      @Override
      public void handle(WindowEvent event) {
        try {
          stop();
        } catch (Exception e) {
          logger.error("error", e);
        }
      }
    });

    ArchiveWindow gui = new ArchiveWindow();
    worker.setBackupEventListener(gui);
    Thread workerThread = new Thread(worker);
    gui.start(stage);
    workerThread.start();
  }

  public static void main(String[] args) {
    logger.debug("AppController.main(),  args = {}", new Object[]{ args });
    launch();
  }

  @Override
  public void stop() throws Exception {
    logger.info("stop() - Archiver was shut down");
    System.exit(0);
  }
}
